package cn.javabb.core.service.sys;

import cn.javabb.common.utils.ListUtils;
import cn.javabb.core.annotation.RedisCache;
import cn.javabb.core.base.BaseService;
import cn.javabb.core.constant.Constant;
import cn.javabb.core.constant.SysConstant;
import cn.javabb.core.entity.sys.UserAuthDO;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.entity.sys.UsersRolesDO;
import cn.javabb.core.mapper.sys.UserMapper;
import cn.javabb.core.model.StatusEnum;
import cn.javabb.core.service.biz.CommentService;
import cn.javabb.core.service.biz.PostService;
import cn.javabb.core.service.blog.BlogService;
import cn.javabb.core.util.EndecryptUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jarvis.cache.annotation.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class UserService extends BaseService<UserDO> {
    @Autowired
    UserMapper userMapper;

    @Autowired
    private UsersRolesService usersRolesService;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private PostService postService;
    @Autowired
    private BlogService blogService;
    @Autowired
    private CommentService commentService;
    /**
     * 分页查询用户
     * @author QINB
     * @param param
     * @return
     */
    public Page listUserPage(JSONObject param){
        param.put("sqlid", UserMapper.class.getName()+".listUser");
        Page p = this.queryListPage(param);
        return p;
    }
    
    /**
     * 通过用户名获取用户
     * @author QINB
     * @param userName
     * @return
     */
    public UserDO getByUserName(String userName){
        JSONObject param = new JSONObject();
        param.put("userName",userName);
        param.put(SQLID, UserMapper.class.getName()+".queryByUserName");
        UserDO user = this.queryOne(param);
        if(null != user){
            user.setIsAdmin(isAdmin(user.getId()));
            return user;
        }
        return null;
    }

    /**
     * 更新用户的状态
     * @author QINB
     * @param ids
     * @param state
     * @return
     */
    public boolean updateState(String ids, Integer state) {
        List<String> idList = ListUtils.stringToListString(ids);
        Example ex = new Example(UserDO.class);
        ex.createCriteria().andIn("id", idList);
        UserDO user = new UserDO();
        user.setState(state);
        return this.userMapper.updateByExampleSelective(user, ex)>0;
        //return this.updateSelective(user)>0?true:false;
    }
    /**
     * 是否是超级管理员
     * @author QINB
     * @param userId
     * @return
     */
    public Boolean isAdmin(Integer userId){
        UsersRolesDO ur = new UsersRolesDO();
        ur.setUserId(userId);
        List<UsersRolesDO> urList = usersRolesService.queryListByWhere(ur);
        if(ListUtils.isNotEmpty(urList)){
            for(UsersRolesDO t:urList){
                if(t.getRoleId() == SysConstant.ADMIN_ROLE_ID){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取用户的积分排名
     * @param size
     * @return
     */
    @RedisCache
    public List<UserDO> listRankUsers(Integer size){
        if(null==size||size==0){size = 0;}
        Example ex = new Example(UserDO.class);
        ex.createCriteria().andEqualTo("state", StatusEnum.NORMAL.getCode());
        ex.orderBy("money").desc();
        PageHelper.startPage(1,size);
        return this.queryListByExample(ex);
    }

    /**
     * 获取用户总数
     * @return
     */
    public Integer CountUser(){
        return this.queryCountByWhere(new UserDO());
    }

    /**
     * 获取最新的一个用户
     * @return
     */
    @Cache(key = "lastestUser",expire = 200)
    public UserDO lastestUser(){
        Example ex = new Example(UserDO.class);
        ex.orderBy("createTime").desc();
        PageHelper.startPage(1,1);
        return this.queryListByExample(ex).get(0);
    }

    /**
     * 查询用户是否重复 return true 重复
     * @param username
     * @return
     */
    public boolean queryUsernameRepeat(String username){
        UserDO user = new UserDO().setUserName(username).setState(StatusEnum.NORMAL.getCode());
        if(this.queryCountByWhere(user)>0){
            return true;
        }
        return false;
    }

    /**
     * 更新最后登录时间
     * @param userId
     * @return
     */
    public boolean updateUserLastLoginTime(Integer userId){
        UserDO user = new UserDO().setId(userId).setLastLoginTime(new Date());
        if (this.updateSelective(user) > 0) {
            return true;
        }
        return false;
    }
    @Transactional
    public UserDO addUser(UserDO user,String userPwd){
                user.setUserGrade(SysConstant.USER_GRADE_GENERAL)
                //.setUserPwd(EndecryptUtil.encrytMd5(user.getUserPwd()))
                .setState(StatusEnum.NORMAL.getCode())
                .setEmailVerified(0)
                .setNickName(user.getUserName())
                .setMoney(Constant.INIT_MONEY)
                .setUserImg(Constant.DEFAULT_USERIMG);
        ;

        if(this.insertSelective(user)>0){
            UserAuthDO userAuth = new UserAuthDO()
                    .setUserId(user.getId())
                    .setAuthPwd(EndecryptUtil.encrytMd5(userPwd))
                    .setAuthType(userAuthService.getAuthType(user.getUserName())) //普通账号
                    .setState(StatusEnum.NORMAL.getCode())
                    ;
            if (userAuthService.insertSelective(userAuth) > 0) {
                return user;
            }
        }
        return null;
    }

    /**
     * 刷新用户
     * @param id
     * @param request
     */
    public void refreshSessionUser(Integer id, HttpServletRequest request){
        UserDO user = this.queryById(id);
        request.getSession().setAttribute(Constant.SESSION_USER,user);
    }

    /**
     * 用户评论排行榜
     * @return
     */
    @Cache(key = "rankUserComment",expire = 20*60)
    public List<UserDO> rankUserComment(){

        PageHelper.startPage(1,8);
        List<UserDO> list = userMapper.listUserWithComment();
        return list;
    }

    /**修改用户等级，0为普通用户，1为超级VIP，2为至尊VIP
     *
     * @param grade
     * @param userId
     * @return
     */
    public boolean updateUserGrade(int grade, Integer userId) {
        UserDO user = new UserDO().setUserGrade(grade).setId(userId);
        if (this.updateSelectiveNoOther(user) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 修改用户的金币
     * @param gold
     * @param userId
     * @return
     */
    public boolean updateUserGold(int gold, Integer userId) {
        UserDO user  = this.queryById(userId);
        UserDO tempUser = new UserDO().setId(userId).setMoney(user.getMoney() + gold);
        if (this.updateSelectiveNoOther(tempUser) > 0) {
            return true;
        }
        return false;
    }
    // 逻辑删除
    /*public Integer deleteById(String id) {
        UserDO user = new UserDO().setId(Integer.valueOf(id)).setState(StatusEnum.DELETE.getCode());
        return this.updateSelective(user);
    }*/
    /*删除用户*/
    public boolean delete(String ids) {
        List<String> idList = ListUtils.stringToListString(ids);
        int num = 0;
        for (String id : idList) {
            // 删除用户
            num += this.deleteById(id);
            // 删除用户账号
            userAuthService.deleteByWhere(new UserAuthDO().setUserId(Integer.valueOf(id)));
            // 删除用户角色
            usersRolesService.deleteByUserId(Integer.valueOf(id));
            // 删除帖子
            postService.deleteByUserId(Integer.valueOf(id));
            // 删除博客
            blogService.deleteByUserId(Integer.valueOf(id));
        }
        return num>0;
    }

}
